package com.thp.proxy.test;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;


import sun.misc.ProxyGenerator;

public class testComplier extends ClassLoader {

	
	public static void main(String[] args) throws IOException {
		
		testComplier test = new testComplier();
		
		File file = new File("src/com/thp/proxy/model/Person.java");
		
		// System.out.println(file.exists());
		File[] files = new File[]{file};
		
		
		JavaCompiler complier = ToolProvider.getSystemJavaCompiler();
		
		StandardJavaFileManager fileManager = complier.getStandardFileManager(null, null, null);
		
		Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(files);
		
		complier.getTask(null, fileManager, null, null, null, compilationUnits).call();
		
		
		fileManager.close();
		
		
		
		String basePath = testComplier.class.getResource("").getPath();
		
		// System.out.println("basePath: " + basePath);
		File baseDir = new File(basePath);
		
		// System.out.println("baseDir name :" + baseDir.getName());
		
		String className = testComplier.class.getPackage().getName() + "." + "Student";
		
		File classFile = new File(baseDir, "$Student.class");
		
		System.out.println(classFile.getName());
		
		FileInputStream in = null;
		ByteArrayOutputStream out = null;
		try {
			
			in = new FileInputStream(classFile);
			out = new ByteArrayOutputStream();
			byte[] buff = new byte[1024];
			int len;
			while((len = in.read(buff)) != -1) {
				out.write(buff, 0, len);
			}
			
			test.def(className, out.toByteArray(), 0, out.size());
			
			
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(in != null) {
				
				in.close();
			}
			if(out != null) {
				out.close();
			}
		}
		
		
	}
	
	
	private  void def(String className, byte[] byteArray, int i, int size) {
		defineClass(className, byteArray, i, size);
		
	}


	
}
